package com.tencet.dao.impl;

import com.tencet.dao.UserDao;
import com.tencet.entity.OpenAccount;
import com.tencet.entity.User;
import com.tencet.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

/**
 * @author: aiming    @date: 2022/7/21 10:45
 * @description:
 */
public class UserDaoImpl implements UserDao {

    private QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public User findByPhoneNum(String phoneNum) {
        try {
            return qr.query("select * from registered where phone_num = ?",new BeanHandler<User>(User.class),phoneNum);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public int insert(String phoneNum, String password) {
        int update = 0;
        try {
            update = qr.update("insert into registered (phone_num,password) values (?,?)",phoneNum,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    @Override
    public User findByPhoneNumAndPassword(String phoneNum, String password) {
        try {
            return qr.query("select * from registered where phone_num=? and password=?",new BeanHandler<User>(User.class),phoneNum,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据电话修改registered表中开户状态为 1
     * @author  Yangjx
     * @param phoneNum
     * @return
     */
    @Override
    public int update(String phoneNum) {
        int i = 0;
        try {
            i = qr.update("update registered set accounttype=1 where phone_num=?",phoneNum);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 根据登录手机号查二类账户号
     * @author  Yangjx
     * @param phoneNum 登录手机号
     * @return OpenAccount对象
     */
    @Override
    public OpenAccount getSecondAccountNumberByPhone(String phoneNum) {
        try {
            OpenAccount openAccount = qr.query("select * from openaccount where phone=?", new BeanHandler<OpenAccount>(OpenAccount.class), phoneNum);
            return openAccount;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public Integer getAccType(String phoneNum) {
        String sql = "select accounttype from registered where phone_num = ?";
        try {
            return (Integer) qr.query(sql, new ScalarHandler(),phoneNum);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
